/**
 * Created by Administrator on 2017/1/16.
 */

var MJPlayer = require('../MJ/player').MJPlayer;
var MJ = require('../MJ/MJ');
var Const = require('./const');
var SubCode = require('../subCode');

exports.TTMMJPlayer = MJPlayer.extend({
    isDianPao: false,
    menqing: true,
    _fcy: 0,
    _fcyScore: 0,
    init: function(uid, msg) {
        this._super(uid, msg);
        this._stat.zmCount = 0;             // 自摸次数
        this._stat.dpCount = 0;             // 点炮次数
        this._stat.dhCount = 0;             // 点胡次数
        this._stat.anGangCount = 0;        // 暗杠次数
        this._stat.mingGangCount = 0;      // 明杠次数

        this.menqing = true;
        this._stat.roundfengAnGang = 0;        // 本轮风暗杠次数
        this._stat.roundanGang = 0;        // 本轮暗杠次数
        this._stat.roundfengMingGang = 0;      // 本轮风明杠次数
        this._stat.roundmingGang = 0;      // 本轮明杠次数
        this._stat.roundfan = 0;
        this._stat.roundFXK = 0;      // 本轮风向刻次数
        this._stat.roundFAK = 0;      // 本轮风暗刻次数
        this.isDianPao = false;
        this._stat.lzCount = 0;             // 庄家次数
        this._stat._huaCards = [];
        this._stat.roundRules = {};
        this._fcy = 0;
        this._fcyScore = 0;

    },


    settlementGangScore: function() {
        var player = this;
        var room = this.getRoom();

        if (!this.isRoundHu()) {
            return;
        }

        //风向刻
        for (var i = 0, l = player._pengCards.length; i < l; ++i) {
            var card = player._pengCards[i];
            if(!MJ.isBasicColor(MJ.getColor(card))){
                player._stat.roundFXK++;
            }
        }
        //风暗刻
        var cards = this.getRoundHuCards();

        ExObject.eachKeyNum(cards,function(c,n){
            if(!MJ.isBasicColor(MJ.getColor(c))){
                if(n == 3){
                    player._stat.roundFAK++;
                }
            }
        });

        for (var i = 0, l = this._gangCards.length; i < l; ++i) {
            var gangInfo = this._gangCards[i];

            if (gangInfo.gang == MJ.Gang.AN || gangInfo.gang == MJ.Gang.ANS) {
                if (MJ.isBasicColor(MJ.getColor(gangInfo.card))) {
                    this._stat.roundanGang++;
                } else {
                    this._stat.roundfengAnGang++;

                }

            } else {
                if (MJ.isBasicColor(MJ.getColor(gangInfo.card))) {
                    this._stat.roundmingGang++;
                } else {
                    this._stat.roundfengMingGang++;
                }
            }
        }
    },

    settlementPatternScore: function() {
        if (!this.isRoundHu()) {
            return;
        }
        var player = this;
        var room = this.getRoom();
        var subConfig = room.getSubConfig();
        var dpPlayer = room.getPlayerByIndex(room.getFirstDPIndex());

        var ItemFan = this._stat.roundPatternScore;

        var huaScore = this._stat._huaCards.length;
        var keScore = this._stat.roundFAK + this._stat.roundFXK;
        var gangScore = (this._stat.roundanGang * 2) + this._stat.roundmingGang + (this._stat.roundfengAnGang * 3) + (this._stat.roundfengMingGang * 2);
        var diScore = subConfig.options.DI;
        var roundfan = 0;
        var wuhuaguo = false;
        if(huaScore == 0 && gangScore == 0 && keScore == 0){
            wuhuaguo = true;
            //this._stat.roundRules[rule] = 1;
            huaScore =10;
        }
        var shouhua = keScore + gangScore;
        var iTmpScore = keScore + huaScore + gangScore;
        iTmpScore *= subConfig.options.HUA;
        iTmpScore += diScore;

        var rule = Const.ScoreRule.DiFen;
        player.addRoundItemScores(rule,1);
        rule = Const.ScoreRule.shouHua;
        player.addRoundItemScores(rule,shouhua);
        rule = Const.ScoreRule.KeZi;
        player.addRoundItemScores(rule,keScore);
        if(wuhuaguo) {
            rule = Const.ScoreRule.WuHuaGuo;
            player._stat.roundItemScores[rule] = 10;
        }else {
            if(huaScore){
                rule = Const.ScoreRule.HuaFen;
                player.addRoundItemScores(rule,0);
                player._stat.roundItemScores[rule] = huaScore;
            }
        }
        rule = Const.ScoreRule.GangFen;
        player.addRoundItemScores(rule,gangScore);


        // 结算牌型及基础分
        var basicScore = iTmpScore;

        subConfig.options.PATTERN = room.getOption("PX");
        if(subConfig.options.PATTERN){
            ExObject.eachKeyNum(this._stat.roundRules, function(rule, value) {
                player.setRoundScoreRule(rule);
                player.addRoundItemScores(rule,Const.ItemScore[rule]);
                player._stat.roundScoreRules[rule] = Const.ItemScore[rule];
            });
        }
        rule = Const.ScoreRule.HuangFan;
        if(room.HZNUM > 0){
            player.addRoundItemScores(rule,1);
            player.setRoundScoreRule(rule);
        }else {
            player.addRoundItemScores(rule,0);
        }
        roundfan = ExObject.sumValue(this._stat.roundScoreRules);
        this._stat.roundfan = roundfan;

        var score = basicScore;
        roundfan = Math.pow(2, roundfan);
        score *= roundfan;
        if(subConfig.options.PATTERN) {
            score *= ItemFan;
        }
        if(room.isCardRoom()){
            if(subConfig.options.LEZI && score > subConfig.options.LEZI) {
                score = subConfig.options.LEZI;
            }
        }
        if(room.getOption("FCY")){
            var fScore = 0;
            if(MJ.getColor(room._fcy) == MJ.Color.HUA || MJ.getColor(room._fcy) == MJ.Color.ZI){
                fScore = 5 * subConfig.options.HUA;
            }else {
                fScore = MJ.getPoint(room._fcy) * subConfig.options.HUA;
            }
            score += fScore;
            rule = Const.ScoreRule.CangYing;
            player.addRoundItemScores(rule,fScore);
        }
        // 结算每个人的分数
        room.enumPlayers(function(eIndex, ePlayer) {
            if (eIndex == player.getIndex()) {
                return;
            }
            var curscore = score;

            /*if(score > subConfig.options.LEZI) {
                score = subConfig.options.LEZI;
            }*/
            if(player._stat.roundResult == MJ.Result.ZM){  // 三家出
                ePlayer.addRoundScore(-score);
                player.addRoundScore(score);
            }else{
                if(dpPlayer && dpPlayer == ePlayer){
                    player.addRoundScore(score);
                    dpPlayer.addRoundScore(-score);
                }
            }
        });
    },

    settlementRules: function() {
        var rules = this._stat.roundRules;
        var pattern = this._stat.roundPattern;
        var room = this.getRoom();
        var player = this;

        //以下规则只针对赢家有效
        if (!this.isRoundHu()) {
            return;
        }

        // 判断 门清
        var existKaiMenGang = false;
        var existMenQingGang = false;
        this._gangCards.forEach(function (gangInfo) {
            if (gangInfo.gang == MJ.Gang.AN || gangInfo.gang == MJ.Gang.ANS) {
                existMenQingGang = true;
            } else {
                existKaiMenGang = true;
            }
        });
        if (this._chiCards.length == 0 && this._pengCards.length == 0 && !existKaiMenGang) {
            if(this.menqing){
                rules[Const.ScoreRule.MenQing] = 1;
            }
        }
        //牌型

        // 判断 清一色/混一色
        var colors = {};
        var existSpecGang = false;
        var existAnGang = false;

        ExObject.eachKeyNum(this._handCards.getCards(), function (card, num) {
            colors[MJ.getColor(card)] = 1;
        });


        colors[MJ.getColor(this._stat.huCard)] = 1;

        this._pengCards.forEach(function (card) {
            colors[MJ.getColor(card)] = 1;
        });

        this._chiCards.forEach(function (chiInfo) {
            colors[MJ.getColor(chiInfo.card)] = 1;
        });

        this._gangCards.forEach(function (gangInfo) {

            colors[MJ.getColor(gangInfo.card)] = 1;

        });

        var existColorZI = colors.hasOwnProperty(MJ.Color.ZI);

        delete colors[MJ.Color.ZI];
        var colorNum = Object.keys(colors).length;

        if (colorNum == 1) {
            if (existSpecGang || existColorZI) {
                rules[Const.ScoreRule.HunYiSe] = 1;
            } else {
                rules[Const.ScoreRule.QingYiSe] = 1;
            }
        }

        //判断荒番局

    },

    settlement: function() {
        this._super();

        if (this._stat.roundResult == MJ.Result.ZM) {
            this._stat.zmCount++;
        } else if (this._stat.roundResult == MJ.Result.DH) {
            this._stat.dhCount++;
            if (this._stat.roundTarget.length > 0) {
                var dpPlayer = this.getRoom().getPlayerByIndex(this._stat.roundTarget[0]);
                if (dpPlayer) {
                    dpPlayer._stat.dpCount++;
                }
            }
        }

        for (var i = 0, l = this._gangCards.length; i < l; ++i) {
            var gangInfo = this._gangCards[i];
            if (gangInfo.type) {

            } else {
                if (gangInfo.gang == MJ.Gang.AN || gangInfo.gang == MJ.Gang.ANS) {
                    this._stat.anGangCount++;
                } else {
                    this._stat.mingGangCount++;
                }
            }
        }

        if (this.isDealer()) {
            this._stat.lzCount++;
        }
    },

    playHua: function(hua){
        for(var i = 0; i < hua.length; i++){
            this._handCards.play(hua[i]);
            this._stat._huaCards.push(hua);
        }

    },



    /******************************************************************
     * 重载的接口
     ******************************************************************/

    getReconnectInfo: function(isSelf) {
        var info = this._super(isSelf);
        info.gangCards = this._gangCards;
        info.pengCards = this._pengCards;
        info.chiCards = this._chiCards;
        info.handCards = this._handCards.getCards();
        info.remainScore = this._stat.score;

        info.huaCards =  this._stat._huaCards;
        return info;
    },

    getSettlementInfo: function() {
        var info = this._super();
        info.huaCards =  this._stat._huaCards;
        info.gangCards = this._gangCards;
        info.pengCards = this._pengCards;
        info.chiCards = this._chiCards;
        info.remainScore = this._stat.score;
        info.handCards = this._handCards.getCards();
        info.DianPao = this.isDianPao;
        info.roundFanScore = this._stat.roundfan;
        info.roundGangNum = this._gangCards.length;
        info.fcy = this._fcy;
        info.fcyScore = this._fcyScore;
        return info;
    },

    onStartNewRound: function() {
        this._super();
        this._stat.roundfengAnGang = 0;        // 本轮风暗杠次数
        this._stat.roundanGang = 0;        // 本轮暗杠次数
        this._stat.roundfengMingGang = 0;      // 本轮风明杠次数
        this._stat.roundmingGang = 0;      // 本轮明杠次数
        this._stat.roundFXK = 0;      // 本轮风向刻次数
        this._stat.roundFAK = 0;      // 本轮风暗刻次数
        this._stat.roundfan = 0;
        this._stat.roundRules = {};
        this._stat._huaCards = [];
        this.isDianPao = false;
        this.menqing = true;
        this._fcy = 0;
        this._fcyScore = 0;


    },
    isMenQingGang: function(gangInfo) {
        return gangInfo.type || gangInfo.gang == MJ.Gang.AN || gangInfo.gang == MJ.Gang.ANS;
    },

    /**
     * 当前是否是门清状态
     * @private
     */
    nowIsMenQing: function() {
        if (this._pengCards.length > 0) {
            return false;
        }

        if (this._chiCards.length > 0) {
            return false;
        }

        var isMenQing = true;
        this._gangCards.forEach(function (gangInfo) {
            if (!this.isMenQingGang(gangInfo)) {
                isMenQing = false;
            }
        }.bind(this));

        return isMenQing;
    },
    /*gangCard: function(gangTask) {
        var selectGang = gangTask.selectGang || 0;
        if (selectGang > gangTask.gangArray.length) {
            selectGang = 0;
        }

        var selectGangTask = gangTask.gangArray[selectGang];

        if (selectGangTask.type) {
            return this._specGangCard(selectGangTask);
        } else {
            return this._super(selectGangTask);
        }
    },*/
    getInitHandCardPreCards: function() {
        var preCards = [];

        var distance = this.getRoom().getIndexDistance(this.getIndex(), this.getRoom().getDealerIndex());
        if (distance == 3) {
            /*preCards.push(23);
            preCards.push(23);
            preCards.push(14);*/

        }else if(distance == 0){
            /*preCards.push(32);
            preCards.push(33);
            preCards.push(34);

            preCards.push(39);
            preCards.push(39);
            preCards.push(39);

            preCards.push(17);
            preCards.push(18);
            preCards.push(19);

            preCards.push(14);
            preCards.push(14);
            preCards.push(14);
            preCards.push(15);*/

        }
        return preCards;
    },
    getAllHuaNum : function(hucard){
        var player = this;
        var num = player._stat._huaCards.length;
        for (var i = 0, l = player._pengCards.length; i < l; ++i) {
            var card = player._pengCards[i];
            if(!MJ.isBasicColor(MJ.getColor(card))){
                num++;
            }
        }
        //风暗刻
        var cards = clone(this._handCards.getCards());
        ExObject.addNumber(cards, hucard, 1);
        ExObject.eachKeyNum(cards,function(c,n){
            if(!MJ.isBasicColor(MJ.getColor(c))){
                if(n == 3){
                    num++;
                }
            }
        });

        for (var i = 0, l = this._gangCards.length; i < l; ++i) {
            var gangInfo = this._gangCards[i];

            if (gangInfo.gang == MJ.Gang.AN || gangInfo.gang == MJ.Gang.ANS) {
                if (MJ.isBasicColor(MJ.getColor(gangInfo.card))) {
                    num += 2;
                } else {
                    num += 3;
                }

            } else {
                if (MJ.isBasicColor(MJ.getColor(gangInfo.card))) {
                    num += 1;

                } else {
                    num += 2;
                }
            }
        }
        return num;
    },
    getCurFan: function(){
        var room = this.getRoom();
        var fannum = 0;
        //清一色
        var colors = {};
        var existSpecGang = false;
        var existAnGang = false;
        ExObject.eachKeyNum(this._handCards.getCards(), function (card, num) {
            colors[MJ.getColor(card)] = 1;
        });
        colors[MJ.getColor(this._stat.huCard)] = 1;
        this._pengCards.forEach(function (card) {
            colors[MJ.getColor(card)] = 1;
        });
        this._chiCards.forEach(function (chiInfo) {
            colors[MJ.getColor(chiInfo.card)] = 1;
        });
        this._gangCards.forEach(function (gangInfo) {
            colors[MJ.getColor(gangInfo.card)] = 1;
        });
        var existColorZI = colors.hasOwnProperty(MJ.Color.ZI);
        delete colors[MJ.Color.ZI];
        var colorNum = Object.keys(colors).length;
        if (colorNum == 1) {
            if (existSpecGang || existColorZI) {
                fannum += 1;
            } else {
                fannum += 2;
            }
        }
        //荒番
        if(room.HZNUM > 0){
            fannum += 1;
        }
        return fannum;
    },
    setBaoTing: function() {
        this._isBaoTing = true;
        var room = this.getRoom();
        //room._passTing = 1;
    },
    setRoundRule: function(key){
        this._stat.roundRules[key] = 1;
    },
    cancelLastGangForQG: function(card) {
        var gangIndex = this._gangCards.length - 1;
        if (gangIndex < 0) {
            return;
        }

        var gangInfo = this._gangCards[gangIndex];
        if (gangInfo.type) {
            if (gangInfo.buCard != card) {
                return;
            }

            if (gangInfo.buCards.length < 1) {
                return;
            }

            gangInfo.buCards.splice(gangInfo.buCards.length - 1, 1);
            gangInfo.buCard = (gangInfo.buCards.length > 0) ? gangInfo[gangInfo.buCards.length - 1] : 0;
        } else {
            return this._super(card);
        }
    },

    checkHua: function(){
        var hua = [];
        ExObject.eachKeyNum(this._handCards.getCards(), function(c, n) {
            if(MJ.getColor(c) == MJ.Color.HUA){
                hua.push(c);
            }else if(c == MJ.ZI.HZ || c == MJ.ZI.FC || c == MJ.ZI.BB){
                for(var i = 0; i < n; i++){
                    hua.push(c);
                }
            }
        });
        return hua;
    },
    /*checkTingcard: function(cards) {
        var tings = [];

        if (!this.checkTingOrHuCondition()) {
            return tings;
        }

        var subConfig = this.getRoom().getSubConfig();


        subConfig.colors.forEach(function(color) {
            if (color == this.getSelectColor()) {
                return;
            }

            var cardNum = MJ.ColorCardNum[color];
            for (var p = 1, pm = cardNum.point; p <= pm; ++p) {
                var card = MJ.getValue(color, p);
                if (cards[card] === 4) {
                    continue;
                }

                var tmpCards = clone(cards);
                ExObject.addNumber(tmpCards, card, 1);

                var pattern = this.checkHuLogic(tmpCards, card);
                if (pattern != MJ.Pattern.NONE) {
                    tings.push({card: card, pattern: pattern});
                }
            }
        }.bind(this));

        return tings;
    },*/
    /*checkBaoTing: function(){
        var cards = this._handCards.getCards();

        var playcard = {};
        var player = this;
        ExObject.eachKeyNum(cards, function(c,n){
            var newcards = clone(cards);
            newcards[c] -= 1;
            var tings = player.checkTingcard(newcards);
            if(tings.length > 0){
                ExObject.addNumber(playcard,c,tings);
            }
        });
        var cardsNum = MJ.sumCardsNum(cards);
    },*/
    checkTingOrHuCondition: function(){
        // 定缺
        if (this.getRoom().isSelectColor()) {
            if (MJ.existColor(this._handCards.getCards(), this.getSelectColor())) {
                return false;
            }
        }
        var hua = this.checkHua();
        if(hua.length > 0){
            return false;
        }
        return true;
    },
    checkHuCondition: function(card){
        if(this._chiCards.length > 0 || this._pengCards.length > 0){
            if(this.getAllHuaNum(card) == 1){
                return false;
            }
        }
        return true;

    },
    checkTingChangeIfGangInTTM: function(gangTask) {
        this.gangCard(gangTask);
        var tings = this.checkTing();
        this.cancelLastGang();

        var oldTings = this.getTingCards();
        if (tings.length != oldTings.length) {
            return true;
        }
        var change = false;
        for (var i = 0, il = tings.length; i < il; ++i) {
            var ting = tings[i];
            var exist = false;
            for (var io = 0, iol = oldTings.length; io < iol; ++io) {
                if (oldTings[io].card == ting.card) {
                    exist = true; break;
                }
            }
            if (!exist) {
                change = true;
            }
        }
        console.log("oldTings = %j, curtings = %j, change = %f", oldTings, tings, change);

        return change;
    },
    checkChiCondition: function(card) {
        var subConfig = this.getRoom().getSubConfig();
        var color = MJ.getColor(card);
        if (subConfig.colors.indexOf(color) == -1) {
            return false;
        }

        if (!MJ.isBasicColor(color)) {
            return false;
        }

        return true;
    },
    /*checkHuIfGang: function(gangcard){
        var cards = this._handCards.getCards();
        var tings = this.checkTingcard(newcards);
        var newcards = clone(cards);
        newcards[gangcard] = 0;
        var ting = this.checkTingcard(newcards);
        if(ting.length > 0){
            return true;
        }
        return false;
    },*/
    /*checkGangWithCard: function(card){
        if (this.getRoom().isSelectColor()) {
            if (MJ.getColor(card) == this.getSelectColor()) {
                return false;
            }
        }
        var gang = false;
        if(this._handCards.getCardNum(card) == 3){
            if(this.isBaoTing()){
                gang = this.checkHuIfGang(card);
            }else {
                gang = true;
            }
        }
        return gang;
    },*/
    /**
     * 检查杠
     * @returns []
     */
   /* checkGang: function() {
        var room = this.getRoom();
        var gangArray = [];
        var player = this;

        var lastCard = this._handCards.getLastNewCard();
        if (this.getIndex() != room.getCurPlay() || room.getCurTask()) {
            lastCard = 0;
        }

        if (lastCard) { //优先杠刚摸上的牌
            if (this._handCards.getCardNum(lastCard) == 4) {
                if(this.isBaoTing()){
                    if(this.checkHuIfGang(lastCard))
                        gangArray.push({card:lastCard, gang:MJ.Gang.AN});
                }else {
                    gangArray.push({card:lastCard, gang:MJ.Gang.AN});

                }
            }
            if (this._pengCards.indexOf(lastCard) != -1) {
                gangArray.push({card:lastCard, gang:MJ.Gang.BA});
            }
        }

        var anGangCards = this._handCards.getAnGangCards();
        for (var i = 0; i < anGangCards.length; ++i) {
            if (anGangCards[i] != lastCard) {
                if(this.isBaoTing()){
                    if(this.checkHuIfGang(anGangCards[i])){
                        var gangInfo = {card:anGangCards[i], gang:MJ.Gang.ANS};
                        if (this.getRoom().getHideOption("anGangOverdue")) {
                            if (this.getPlayHand() != this.getRoom().getCurGang()) {
                                gangInfo.overdue = true;
                            }
                        }
                        gangArray.push(gangInfo);
                    }
                }else {
                    var gangInfo = {card:anGangCards[i], gang:MJ.Gang.ANS};
                    if (this.getRoom().getHideOption("anGangOverdue")) {
                        if (this.getPlayHand() != this.getRoom().getCurGang()) {
                            gangInfo.overdue = true;
                        }
                    }
                    gangArray.push(gangInfo);
                }
            }
        }

        this._pengCards.forEach(function(card) {
            if (this._handCards.getCardNum(card) > 0) {
                if (card != lastCard) {
                    if(this.isBaoTing()){
                        if (this.checkHuIfGang(card)) {
                            gangArray.push({card: card, gang: MJ.Gang.BA, overdue: true});
                        }
                    }else {
                        gangArray.push({card: card, gang: MJ.Gang.BA, overdue: true});

                    }

                }
            }
        }.bind(this));

        var from = this.getIndex();
        gangArray.forEach(function(gangInfo) {
            gangInfo.from = from;
        });

        return gangArray;
    },
*/
    checkHuLogic: function(cards, huCard) {
        var num4 = 0;
        var num3 = 0;
        var num2 = 0;
        var num = 0;

        ExObject.each(cards, function(c, n) {
            if (n == 2) {
                num2++;
            } else if (n == 3) {
                num3++;
            } else if (n == 4) {
                num4++;
            }
            num += n;
        });

        if (num2 == 1 && (num3*3 + 2) == num && this._chiCards.length == 0) { // 大对子
            return MJ.Pattern.PAIR;
        }
        if (num == 2 ) { // 单调/大吊车
            return (num2 == 1) ? MJ.Pattern.SINGLE : MJ.Pattern.NONE;
        }
        if ((num2 + num4*2) == 7) { // 七对
            return MJ.Pattern.PAIR7;
        }

        var room = this.getRoom();
        var colors = room.getSubConfig().colors;
        var pattern = MJ.Pattern.NORMAL;
        for (var i = 0, l = colors.length; i < l; ++i) {
            var color = colors[i];
            var colorCards = MJ.getColorCards(cards, color);

            if (MJ.isBasicColor(color)) {
                if (!MJ.checkHuColorCards(MJ.getValue(color, 1), MJ.getValue(color, MJ.COLOR_CARD_NUM), colorCards)) {
                    pattern = MJ.Pattern.NONE; break;
                }
            } else {
                if (!MJ.checkPairHuColorCards(colorCards)) {
                    pattern = MJ.Pattern.NONE; break;
                }
            }
        }
        return pattern;
    },

    _existKaiMenGang: function() {
        var exist = false;
        this._gangCards.forEach(function (gangInfo) {
            if (gangInfo.type || gangInfo.gang == MJ.Gang.AN || gangInfo.gang == MJ.Gang.ANS) {
                // 不算开门
            } else {
                exist = true;
            }
        });
        return exist;
    },

});